/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.json.parser;

import java.math.BigDecimal;
import java.math.BigInteger;

import org.zhiqim.kernel.json.JsonParser;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.util.Ints;
import org.zhiqim.kernel.util.Longs;

/**
 * 基本类型适配器，8种基本类型&null&字符串
 * 1、char和String在toString时要加引号
 * 2、Fastjson/Jackson仅支持（'true', 'false' or 'null'）,即null和boolean类型的字符串
 * 3、Fastjson/Jackson不支持char/String转为对象，Gson支持，这里采用Gson方案
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class BaseParser implements JsonParser
{
    @Override
    public String toString(Object obj)
    {
        if (obj instanceof String)
        {//要对引号进行增加转义
            String str = Jsons.addEscapeChar((String)obj, '\"');
            return new StringBuilder("\"").append(str).append("\"").toString();
        }
        else if (obj instanceof Character)
        {//字符类型要加引号
            return new StringBuilder("\"").append((Character)obj).append("\"").toString();
        }

        return String.valueOf(obj);
    }
    
    @Override
    public Object toObject(String json, Class<?> cls)
    {
        //去掉前后可能的引号
        json = Jsons.removeStartEndQuotation(json);
        
        if (cls == boolean.class || cls == Boolean.class)
            return Boolean.parseBoolean(json);
        else if (cls == byte.class || cls == Byte.class)
            return Byte.parseByte(json);
        else if (cls == char.class || cls == Character.class)
            return json.charAt(0);
        else if (cls == short.class || cls == Short.class)
            return Short.parseShort(json);
        else if (cls == int.class || cls == Integer.class)
            return Ints.toInt(json);
        else if (cls == long.class || cls == Long.class)
            return Longs.toLong(json);
        else if (cls == float.class|| cls == Float.class)
            return Float.parseFloat(json);
        else if (cls == double.class || cls == Double.class)
            return Double.parseDouble(json);
        else if (cls == BigInteger.class)
            return new BigInteger(json);
        else if (cls == BigDecimal.class)
            return new BigDecimal(json);
        else if (cls == String.class)
            return Jsons.removeEscapeChar(json);//字符串要求删除转义
        else
            return null;
    }
}
